/**
 * 电机故障信息模块前端交互脚本
 */

// API基础路径
let knowledgeFailureAPI_BASE = '/api/feibiao/knowledge/failure';

// 将在DOMContentLoaded中初始化
document.addEventListener('DOMContentLoaded', function() {
    try {
        // 确保全局API_BASE已定义
        if (typeof API_BASE !== 'undefined') {
            knowledgeFailureAPI_BASE = `${API_BASE}/feibiao/knowledge/failure`;
        } else {
            console.warn('全局API_BASE未定义，使用默认API路径');
            knowledgeFailureAPI_BASE = '/api/feibiao/knowledge/failure';
        }
        
        // 添加样式
        addStyles();
        
        // 设置事件监听器
        setupEventListeners();
    } catch (err) {
        console.error("电机故障信息模块初始化失败:", err);
    }
});

/**
 * 添加模块所需样式
 */
function addStyles() {
    // 创建样式元素
    const style = document.createElement('style');
    style.textContent = `
        .search-result-info {
            margin-top: 10px;
            padding: 8px 12px;
            background-color: #f8f9fa;
            border-left: 3px solid #007bff;
            font-size: 14px;
            color: #495057;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .search-result-info a {
            color: #007bff;
            text-decoration: none;
            font-weight: 500;
        }
        
        .search-result-info a:hover {
            text-decoration: underline;
        }
        
        .status-success {
            color: #28a745;
            font-weight: 500;
        }
        
        .status-pending {
            color: #dc3545;
            font-weight: 500;
        }
    `;
    
    // 添加到文档头部
    document.head.appendChild(style);
}

/**
 * 加载电机故障信息列表（分页）
 */
function loadKnowledgeFailureList(page = 0, size = 10) {
    // 清除搜索结果提示（如果有）
    const existingSearchInfo = document.querySelector('.search-result-info');
    if (existingSearchInfo) {
        existingSearchInfo.remove();
    }
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    if (!mainContent) return;
    
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求
    fetch(`${knowledgeFailureAPI_BASE}?page=${page}&size=${size}&sort=id,asc`)
        .then(response => {
            if (!response.ok) {
                throw new Error('请求失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            renderKnowledgeFailureTable(data);
        })
        .catch(error => {
            console.error('获取电机故障信息数据失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h2>加载数据失败</h2>
                    <p>错误信息: ${error.message}</p>
                    <div class="error-actions">
                        <button class="btn btn-primary" onclick="loadKnowledgeFailureList()">重试</button>
                    </div>
                </div>
            `;
            if (typeof showMessage === 'function') {
                showMessage('获取电机故障信息数据失败: ' + error.message, 'error');
            }
        });
}

/**
 * 渲染电机故障信息表格
 */
function renderKnowledgeFailureTable(data) {
    const mainContent = document.getElementById('mainContent');
    if (!mainContent) return;
    
    // 构建HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机故障信息管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showKnowledgeFailureForm()"></i> 新增</button>
            </div>
        </div>
        
        <div class="content-toolbar">
            <div class="search-box">
                <input type="text" class="search-input" id="knowledgeFailureSearchInput" placeholder="请输入电机ID搜索...">
                <button class="search-btn" onclick="searchKnowledgeFailure()">搜索</button>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>故障ID</th>
                        <th>电机ID</th>
                        <th>故障类型</th>
                        <th>故障时间</th>
                        <th>发现时间</th>
                        <th>修复状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    // 填充数据行
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.motorId}</td>
                    <td>${item.failureType}</td>
                    <td>${formatDate(item.failureTime)}</td>
                    <td>${formatDate(item.discoveryTime)}</td>
                    <td>${item.repairTime ? '<span class="status-success">已修复</span>' : '<span class="status-pending">未修复</span>'}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewKnowledgeFailure('${item.id}')">查看</a>
                        <a href="javascript:void(0)" onclick="editKnowledgeFailure('${item.id}')">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteKnowledgeFailure('${item.id}')">删除</a>
                    </td>
                </tr>`;
        });
    } else {
        html += '<tr><td colspan="7" style="text-align:center;">暂无数据</td></tr>';
    }
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    // 添加分页控件 - 改为与knowledge_basic.js一致的分页样式
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${data.number <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number <= 0 ? 'void(0)' : 'loadKnowledgeFailureList(' + (data.number - 1) + ', ' + data.size + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === data.number) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadKnowledgeFailureList(${i}, ${data.size})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${data.number >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number >= data.totalPages - 1 ? 'void(0)' : 'loadKnowledgeFailureList(' + (data.number + 1) + ', ' + data.size + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    // 更新内容区域
    mainContent.innerHTML = html;
    
    // 搜索框回车事件
    const searchInput = document.getElementById('knowledgeFailureSearchInput');
    if (searchInput) {
        searchInput.addEventListener('keyup', function(event) {
            if (event.key === 'Enter') {
                searchKnowledgeFailure();
            }
        });
    }
}

/**
 * 搜索电机故障信息
 */
function searchKnowledgeFailure() {
    const motorId = document.getElementById('knowledgeFailureSearchInput').value.trim();
    
    // 检查输入是否为空
    if (!motorId) {
        if (typeof showMessage === 'function') {
            showMessage('请输入电机ID进行搜索', 'warning');
        }
        return;
    }
    
    // 清除先前的搜索结果提示（如果有）
    const existingSearchInfo = document.querySelector('.search-result-info');
    if (existingSearchInfo) {
        existingSearchInfo.remove();
    }
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">正在搜索电机ID为 ' + motorId + ' 的故障信息...</div>';
    
    // 使用电机ID专门的搜索端点 - 修正路径
    fetch(`${knowledgeFailureAPI_BASE}/motor/${encodeURIComponent(motorId)}?sort=id,asc`)
        .then(response => {
            if (!response.ok) {
                throw new Error('搜索请求失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            // 由于后端返回的是List而不是Page对象，需要适配前端分页组件
            const pageData = {
                content: data,
                totalElements: data.length,
                totalPages: 1,
                number: 0,
                size: data.length,
                first: true,
                last: true
            };
            
            renderKnowledgeFailureTable(pageData);
            
            // 在表格上方显示搜索结果提示
            const searchInfo = document.createElement('div');
            searchInfo.className = 'search-result-info';
            searchInfo.innerHTML = `当前显示: 电机ID为 <strong>${motorId}</strong> 的故障信息 (${data.length || 0}条记录)
                <a href="javascript:void(0)" onclick="loadKnowledgeFailureList()">显示全部</a>`;
            
            const toolbar = document.querySelector('.content-toolbar');
            if (toolbar) {
                toolbar.appendChild(searchInfo);
            }
        })
        .catch(error => {
            console.error('搜索失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('搜索失败: ' + error.message, 'error');
            }
            loadKnowledgeFailureList(); // 失败时加载所有数据
        });
}

/**
 * 显示电机故障信息表单（新增或编辑）
 */
function showKnowledgeFailureForm(failureData = null) {
    const mainContent = document.getElementById('mainContent');
    if (!mainContent) {
        console.error('找不到主内容区域元素');
        return;
    }
    
    const isEdit = !!failureData;
    const title = isEdit ? '编辑电机故障信息' : '添加电机故障信息';
    
    // 故障类型选项
    const failureTypes = [
        '短路', '过热', '绝缘损坏', '轴承故障', '绕组故障',
        '机械故障', '电气故障', '控制系统故障', '其他'
    ];
    
    // 创建表单HTML
    // 更新内容区域
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">${title}</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadKnowledgeFailureList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        
        <form id="knowledgeFailureForm" class="data-form" onsubmit="saveKnowledgeFailure(event)">
            <!-- 隐藏ID字段（编辑模式下使用） -->
            ${isEdit ? `<input type="hidden" id="id" name="id" value="${failureData.id}">` : ''}
            

            <div class="form-section">
                <h3 class="section-title">基础信息</h3>
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="motorId">电机ID <span class="required">*</span></label>
                        <select class="form-control" id="motorId" name="motorId" required>
                            <option value="">请选择电机</option>
                        </select>
                        <small class="form-text">请从下拉列表中选择一个电机</small>
                    </div>
                    
                    <div class="form-group col-md-6">
                        <label for="failureType">故障类型 <span class="required">*</span></label>
                        <select class="form-control" id="failureType" name="failureType" required>
                            <option value="">请选择故障类型</option>
                            ${failureTypes.map(type => `
                                <option value="${type}" ${isEdit && failureData.failureType === type ? 'selected' : ''}>
                                    ${type}
                                </option>
                            `).join('')}
                        </select>
                        <small class="form-text">最大长度50个字符</small>
                    </div>
                </div>
            </div>
            

            <div class="form-section">
                <h3 class="section-title">时间信息</h3>
                <div class="form-row">
                    <div class="form-group col-md-4">
                        <label for="failureTime">故障发生时间 <span class="required">*</span></label>
                        <input type="datetime-local" class="form-control" id="failureTime" name="failureTime" required 
                            value="${isEdit ? formatDateTimeLocal(failureData.failureTime) : ''}"
                            onchange="validateFailureTime()">
                        <small class="form-text">故障实际发生的时间</small>
                    </div>
                    
                    <div class="form-group col-md-4">
                        <label for="discoveryTime">故障发现时间 <span class="required">*</span></label>
                        <input type="datetime-local" class="form-control" id="discoveryTime" name="discoveryTime" required 
                            value="${isEdit ? formatDateTimeLocal(failureData.discoveryTime) : ''}"
                            onchange="validateDiscoveryTime()">
                        <small class="form-text">故障被发现的时间</small>
                    </div>
                    
                    <div class="form-group col-md-4">
                        <label for="repairTime">修复完成时间</label>
                        <input type="datetime-local" class="form-control" id="repairTime" name="repairTime"
                            value="${isEdit && failureData.repairTime ? formatDateTimeLocal(failureData.repairTime) : ''}"
                            onchange="validateRepairTime()">
                        <small class="form-text">如果已修复，请填写修复完成时间</small>
                    </div>
                </div>
            </div>
            

            <div class="form-section">
                <h3 class="section-title">详细信息</h3>
                
                <div class="form-group">
                    <label for="failureDescription">故障描述 <span class="required">*</span></label>
                    <textarea class="form-control" id="failureDescription" name="failureDescription" rows="3" required 
                        placeholder="请详细描述故障现象...">${isEdit ? failureData.failureDescription : ''}</textarea>
                    <small class="form-text">详细描述故障的现象、表现等信息</small>
                </div>
                
                <div class="form-group">
                    <label for="failureCause">故障原因 <span class="required">*</span></label>
                    <textarea class="form-control" id="failureCause" name="failureCause" rows="3" required maxlength="100"
                        placeholder="请简要说明故障的根本原因...">${isEdit ? failureData.failureCause : ''}</textarea>
                    <small class="form-text">最多输入100个字符</small>
                </div>
                
                <div class="form-group">
                    <label for="repairMeasures">维修措施 <span class="required">*</span></label>
                    <textarea class="form-control" id="repairMeasures" name="repairMeasures" rows="3" required
                        placeholder="请详细描述采取的维修措施...">${isEdit && failureData.repairMeasures ? failureData.repairMeasures : ''}</textarea>
                    <small class="form-text">详细描述维修过程和采取的措施</small>
                </div>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadKnowledgeFailureList()">取消</button>
            </div>
        </form>
    `;
    
    // 加载电机列表
    loadMotorList();
}

/**
 * 加载电机列表
 */
function loadMotorList() {
    fetch(`${knowledgeFailureAPI_BASE}/motors`)
        .then(response => {
            if (!response.ok) {
                throw new Error('加载电机列表失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            const motorSelect = document.getElementById('motorId');
            
            // 清空选择框
            while (motorSelect.firstChild) {
                motorSelect.removeChild(motorSelect.firstChild);
            }
            
            // 添加默认选项
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '请选择电机';
            motorSelect.appendChild(defaultOption);
            
            // 添加电机选项
            data.forEach(motor => {
                const option = document.createElement('option');
                option.value = motor.motorId;
                option.textContent = `${motor.motorId} - ${motor.motorType || '未知型号'} (${motor.manufacturer || '未知厂商'})`;
                motorSelect.appendChild(option);
            });
            
            // 如果是编辑模式，设置选中值
            const form = document.getElementById('knowledgeFailureForm');
            if (form && form.querySelector('input[type="hidden"][id="id"]')) {
                const formData = new FormData(form);
                const id = formData.get('id');
                if (id) {
                    // 加载编辑数据
                    fetch(`${knowledgeFailureAPI_BASE}/${id}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data && data.motorId) {
                                motorSelect.value = data.motorId;
                            }
                        })
                        .catch(error => console.error('加载编辑数据出错:', error));
                }
            }
        })
        .catch(error => {
            console.error('加载电机列表失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('加载电机列表失败: ' + error.message, 'error');
            }
        });
}

/**
 * 验证故障时间
 */
function validateFailureTime() {
    const failureTime = new Date(document.getElementById('failureTime').value);
    const discoveryTime = new Date(document.getElementById('discoveryTime').value);
    
    if (failureTime > discoveryTime) {
        showMessage('故障发生时间不能晚于发现时间', 'error');
        document.getElementById('failureTime').value = '';
    }
}

/**
 * 验证发现时间
 */
function validateDiscoveryTime() {
    const failureTime = new Date(document.getElementById('failureTime').value);
    const discoveryTime = new Date(document.getElementById('discoveryTime').value);
    const repairTime = document.getElementById('repairTime').value ? 
        new Date(document.getElementById('repairTime').value) : null;
    
    if (discoveryTime < failureTime) {
        showMessage('发现时间不能早于故障发生时间', 'error');
        document.getElementById('discoveryTime').value = '';
    }
    
    if (repairTime && discoveryTime > repairTime) {
        showMessage('发现时间不能晚于修复时间', 'error');
        document.getElementById('discoveryTime').value = '';
    }
}

/**
 * 验证修复时间
 */
function validateRepairTime() {
    const discoveryTime = new Date(document.getElementById('discoveryTime').value);
    const repairTime = new Date(document.getElementById('repairTime').value);
    
    if (repairTime < discoveryTime) {
        showMessage('修复时间不能早于发现时间', 'error');
        document.getElementById('repairTime').value = '';
    }
}

/**
 * 保存电机故障信息（新增或更新）
 */
function saveKnowledgeFailure(event) {
    if (event) {
        event.preventDefault();
    }
    
    // 获取表单数据
    const id = document.getElementById('id')?.value;
    const motorId = document.getElementById('motorId').value.trim();
    const failureType = document.getElementById('failureType').value.trim();
    const failureTime = document.getElementById('failureTime').value;
    const discoveryTime = document.getElementById('discoveryTime').value;
    const repairTime = document.getElementById('repairTime').value;
    const failureDescription = document.getElementById('failureDescription').value.trim();
    const failureCause = document.getElementById('failureCause').value.trim();
    const repairMeasures = document.getElementById('repairMeasures').value.trim();
    
    // 表单验证
    if (!motorId || !failureType || !failureTime || !discoveryTime || !failureDescription || !failureCause || !repairMeasures) {
        if (typeof showMessage === 'function') {
            showMessage('请填写所有必填字段', 'error');
        } else {
            alert('请填写所有必填字段');
        }
        return;
    }
    
    // 字段长度验证
    if (failureType.length > 50) {
        showMessage('故障类型不能超过50个字符', 'error');
        return;
    }
    
    if (failureCause.length > 100) {
        showMessage('故障原因不能超过100个字符', 'error');
        return;
    }
    
    // 构建数据对象
    const failureData = {
        motorId,
        failureType,
        failureTime: new Date(failureTime).toISOString(),
        discoveryTime: new Date(discoveryTime).toISOString(),
        repairTime: repairTime ? new Date(repairTime).toISOString() : null,
        failureDescription,
        failureCause,
        repairMeasures
    };
    
    // 如果是编辑，添加ID
    if (id) {
        failureData.id = parseInt(id);
    }
    
    // 显示加载中提示
    if (typeof showMessage === 'function') {
        showMessage('正在保存数据...', 'info');
    }
    
    // 确定请求方法和URL
    const method = id ? 'PUT' : 'POST';
    const url = id ? `${knowledgeFailureAPI_BASE}/${id}` : knowledgeFailureAPI_BASE;
    
    // 发送请求
    fetch(url, {
        method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(failureData)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                try {
                    const error = JSON.parse(text);
                    throw new Error(error.message || error.error || '保存失败');
                } catch (e) {
                    throw new Error(text || '保存失败');
                }
            });
        }
        return response.json();
    })
    .then(data => {
        // 显示成功消息
        if (typeof showMessage === 'function') {
            showMessage(`${id ? '更新' : '创建'}成功!`, 'success');
        }
        
        // 重新加载数据
        loadKnowledgeFailureList();
    })
    .catch(error => {
        console.error('保存失败:', error);
        if (typeof showMessage === 'function') {
            showMessage('保存失败: ' + error.message, 'error');
        } else {
            alert('保存失败: ' + error.message);
        }
    });
}

/**
 * 查看电机故障详情
 */
function viewKnowledgeFailure(id) {
    // 发起请求获取详情
    fetch(`${knowledgeFailureAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取详情失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            showKnowledgeFailureDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('获取详情失败: ' + error.message, 'error');
            }
        });
}

/**
 * 显示电机故障详情
 */
function showKnowledgeFailureDetail(data) {
    const mainContent = document.getElementById('mainContent');
    if (!mainContent) {
        console.error('找不到主内容区域元素');
        return;
    }
    
    // 构建详情HTML，只显示与数据库表结构相符的字段
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">电机故障详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadKnowledgeFailureList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        
        <div class="data-detail">
            <!-- 基本信息区域 -->
            <div class="detail-grid">
                <div class="detail-group">
                    <label>故障ID:</label>
                    <div>${data.id || '--'}</div>
                </div>
                
                <div class="detail-group">
                    <label>电机ID:</label>
                    <div>${data.motorId || '--'}</div>
                </div>
                
                <div class="detail-group">
                    <label>故障类型:</label>
                    <div>${data.failureType || '--'}</div>
                </div>
            </div>
            
            <!-- 时间信息区域 -->
            <div class="detail-grid time-grid">
                <div class="detail-group">
                    <label>故障发生时间:</label>
                    <div>${formatDate(data.failureTime) || '--'}</div>
                </div>
                
                <div class="detail-group">
                    <label>故障发现时间:</label>
                    <div>${formatDate(data.discoveryTime) || '--'}</div>
                </div>
                
                <div class="detail-group">
                    <label>修复完成时间:</label>
                    <div>${data.repairTime ? formatDate(data.repairTime) : '未修复'}</div>
                </div>
            </div>
            
            <!-- 详细信息区域 -->
            <div class="detail-group">
                <label>故障描述:</label>
                <div class="detail-content">
                    <pre>${formatTextarea(data.failureDescription) || '--'}</pre>
                </div>
            </div>
            <div class="detail-group">
                <label>故障原因:</label>
                <div class="detail-content">
                    <pre>${formatTextarea(data.failureCause) || '--'}</pre>
                </div>
            </div>
            <div class="detail-group">
                <label>维修措施:</label>
                <div class="detail-content">
                    <pre>${formatTextarea(data.repairMeasures) || '暂无维修措施'}</pre>
                </div>
            </div>

            
            <!-- 操作按钮 -->
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editKnowledgeFailure('${data.id}')"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteKnowledgeFailure('${data.id}')"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadKnowledgeFailureList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
}

/**
 * 编辑电机故障信息
 */
function editKnowledgeFailure(id) {
    // 发起请求获取数据
    fetch(`${knowledgeFailureAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取数据失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            showKnowledgeFailureForm(data);
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('获取数据失败: ' + error.message, 'error');
            }
        });
}

/**
 * 删除电机故障信息
 */
function deleteKnowledgeFailure(id) {
    // 直接删除，不显示确认框
    fetch(`${knowledgeFailureAPI_BASE}/${id}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                try {
                    const error = JSON.parse(text);
                    throw new Error(error.message || error.error || '删除失败');
                } catch (e) {
                    throw new Error(text || '删除失败');
                }
            });
        }
        
        if (typeof showMessage === 'function') {
            showMessage('删除成功!', 'success');
        }
        loadKnowledgeFailureList();
    })
    .catch(error => {
        console.error('删除失败:', error);
        if (typeof showMessage === 'function') {
            showMessage('删除失败: ' + error.message, 'error');
        }
    });
}

/**
 * 设置事件监听器
 */
function setupEventListeners() {
    // 搜索框回车事件
    const searchInput = document.getElementById('knowledgeFailureSearchInput');
    if (searchInput) {
        searchInput.addEventListener('keyup', function(event) {
            if (event.key === 'Enter') {
                searchKnowledgeFailure();
            }
        });
    }
}

/**
 * 格式化日期时间
 */
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

/**
 * 格式化日期时间为datetime-local输入格式
 */
function formatDateTimeLocal(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toISOString().slice(0, 16);
} 